package com.example.orderflow.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CorsInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置允许跨域的域名，"*"表示允许任意域名跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置允许的方法类型
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        // 设置允许的header类型
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,content-type");
        // 跨域允许时间
        response.setHeader("Access-Control-Max-Age", "3600");
        // 允许携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // 如果是OPTIONS请求，则直接返回200状态码，避免预检请求失败
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(200);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 不需要做任何事情
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 不需要做任何事情
    }
}

